package com.hefan.live.dao;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.cat.common.entity.Page;
import com.cat.tiger.util.CollectionUtils;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.common.orm.dao.CommonDaoImpl;
import com.hefan.live.bean.LiveRoom;
import com.hefan.live.bean.LiveRoomVo;

/**
 * Created by nigle on 2016/9/28.
 */
@Repository
public class LiveRoomDao extends CommonDaoImpl {

	@Resource
	JdbcTemplate jdbcTemplate;

	private static String TABLE_NAME = "live_room";

	public LiveRoom getLiveRoomByUserId(String userId) {
		String sql = "select lr.id,lr.user_id,lr.chat_room_id,lr.live_name,lr.auth_info,lr.type,"
				+ "lr.person_sign,lr.ticket_history,lr.ticket_fact,lr.live_img,lr.location,"
				+ "lr.status,lr.stuff,lr.live_domain,lr.pull_domain,lr.start_time,lr.live_uuid"
				+ " from live_room lr where lr.user_id = ?";
		List<LiveRoom> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<LiveRoom>(LiveRoom.class), userId);
		return CollectionUtils.isNotEmpty(list) ? list.get(0) : null;
	}

	/**
	 * 查询正在直播的liveRoom集合
	 * 
	 * @return
	 */
	public List<LiveRoom> getLivingRoomList() {
		String sql = "select lr.id,lr.user_id,lr.chat_room_id,lr.live_name,lr.auth_info,lr.type,"
				+ "lr.person_sign,lr.ticket_history,lr.ticket_fact,lr.live_img,lr.location,"
				+ "lr.status,lr.stuff,lr.live_domain,lr.pull_domain,lr.start_time,lr.live_uuid"
				+ " from live_room lr where lr.status = " + GlobalConstants.AUTHOR_LIVING;
		List<LiveRoom> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<LiveRoom>(LiveRoom.class));
		return CollectionUtils.isNotEmpty(list) ? list : null;
	}

	/**
	 * 开播时候更新liveroom数据
	 */
	public int updateLiveRoomWhenLiveStart(LiveRoom liveRoom) {
		String sql = "update live_room lr set lr.live_name = ? , lr.live_img = ? , lr.status = ? , lr.type = ? , lr.start_time = ? ,lr.live_uuid = ? where lr.user_id = ? and lr.chat_room_id = ?";
		Object[] o = new Object[] { liveRoom.getLiveName(), liveRoom.getLiveImg(), liveRoom.getStatus(),liveRoom.getType(),liveRoom.getStartTime(),liveRoom.getLiveUuid(),
				liveRoom.getUserId(), liveRoom.getChatRoomId() };
		logger.info("VIP-LIVEROOM-"+sql);
		return jdbcTemplate.update(sql, o);
	}

	/**
	 * 下单后更新直播盒饭收入 ticket_history
	 * 
	 * @param liveRoom
	 * @return
	 */
	public int updateLiveRoomForRebalance(LiveRoom liveRoom) {
		String sql = "update live_room lr set lr.ticket_history = lr.ticket_history + ? where lr.user_id = ?";
		Object[] o = new Object[] { liveRoom.getTicketHistory(), liveRoom.getUserId() };
		return jdbcTemplate.update(sql, o);
	}

	/**
	 * 主播结束直播后更新live_room表中数据
	 */
	public int updateLiveRoomWhenLiveEnd(String userId) {
		Timestamp now = new Timestamp(new Date().getTime());
		String sql = "update live_room lr set lr.status = ? , lr.update_time = ? where lr.user_id = ?";
		Object[] o = new Object[] { GlobalConstants.AUTHOR_LIVEEND, now, userId };
		return jdbcTemplate.update(sql, o);
	}

	/**
	 * 随机推荐主播
	 * 
	 * @return
	 */
	public List<LiveRoom> recommendLive() {
		String sql = "SELECT nick_name nickName , lr.user_id userId, IFNULL(lr.live_img,'') liveImg,"
				+ "head_img headImg,lr.chat_room_id chatRoomId,lr.status status,"
				+ "IFNULL((SELECT llg.watch_num from live_log llg where lr.chat_room_id=llg.chat_room_id   ORDER BY llg.start_time desc LIMIT 1),'') watchNum,"
				+ " IFNULL((SELECT llg.live_uuid from live_log llg where lr.chat_room_id=llg.chat_room_id   ORDER BY llg.start_time desc LIMIT 1),'') liveUuid,"
				+ "IFNULL((SELECT llg.pull_url from live_log llg where lr.chat_room_id=llg.chat_room_id   ORDER BY llg.start_time desc LIMIT 1),'') liveUrl from web_user wu,live_room lr where wu.user_id=lr.user_id and lr.status=1 order by rand() limit 6 ";
		return getJdbcTemplate().query(sql.toString(), new BeanPropertyRowMapper(LiveRoom.class));
	}

	/**
	 * H5：直播间
	 * 
	 * @return
	 */
	public Map<String, Object> findLiveRoomById(String roomId) {
		StringBuilder sql = new StringBuilder();
		sql.append(
				" SELECT wu.user_id userId,lr.status status,ll.watch_num watchNum, IFNULL(wu.head_img,'') headImg,IFNULL(wu.nick_name,'') name,lr.type,lr.live_img liveImg,IFNULL(lr.location,'') location,IFNULL(lr.live_name,'') persionSign,lr.chat_room_id chatRoomId,IFNULL(ll.pull_url,'') liveUrl,IFNULL(ll.live_uuid,'') liveUuid,IFNULL(ll.display_graph,'') displayGraph");
		sql.append(" FROM(live_room lr,web_user wu)");
		sql.append(
				" LEFT JOIN live_log ll ON ll.chat_room_id=lr.chat_room_id WHERE lr.user_id=wu.user_id  and lr.chat_room_id="
						+ roomId);
		sql.append(" ORDER BY ll.start_time  DESC LIMIT 1");
		System.out.println(sql);
		return getJdbcTemplate().queryForMap(sql.toString());
	}

	public LiveRoom getLiveRoomByChatRoomId(int chatRoomId) {
		String sql = "select lr.id,lr.user_id,lr.chat_room_id,lr.live_name,lr.auth_info,lr.type,"
				+ "lr.person_sign,lr.ticket_history,lr.ticket_fact,lr.live_img,lr.location,"
				+ "lr.status,lr.stuff,lr.live_domain,lr.pull_domain,lr.start_time,lr.live_uuid"
				+ " from live_room lr where lr.chat_room_id = ?";
		List<LiveRoom> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<LiveRoom>(LiveRoom.class), chatRoomId);
		return CollectionUtils.isNotEmpty(list) ? list.get(0) : null;
	}

	public List<LiveRoomVo> getLivingListByPage(Page po) {
		StringBuilder sql = new StringBuilder();
		sql.append(
				"SELECT lr.user_id userId,lr.high_status userHStatus from live_room lr where lr.status=1");
		return this.findPage(po, sql.toString(), null, LiveRoomVo.class).getResult();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public LiveRoomVo findLiveRoomByIdFormonitor(String userId, String uuid) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT ll.pull_url,ll.start_time,(select user_type from web_user where user_id=" + userId
				+ " LIMIT 1) userType from live_log ll where user_id=" + userId + " and live_uuid='" + uuid
				+ "' ORDER BY start_time DESC LIMIT 1");
		List<LiveRoomVo> liveRoomVo = getJdbcTemplate().query(sql.toString(),
				new BeanPropertyRowMapper(LiveRoomVo.class));
		return liveRoomVo.get(0);
	}

	public List listHostIndex() {
		StringBuilder sql = new StringBuilder();
		sql.append(
				" (SELECT wu.user_id id,IFNULL(wu.head_img,'') headImg,IFNULL(wu.nick_name,'') name,lr.type,IFNULL(lr.live_img,'') liveImg,IFNULL(lr.location,'') location,IFNULL(lr.live_name,'') personSign,lr.chat_room_id chatRoomId,IFNULL((SELECT llg.pull_url from live_log llg where ll.chat_room_id=llg.chat_room_id   ORDER BY llg.start_time desc LIMIT 1),'') liveUrl,IFNULL((SELECT llg.live_uuid from live_log llg where ll.chat_room_id=llg.chat_room_id   ORDER BY llg.start_time desc LIMIT 1),'') liveUuid,IFNULL(ll.display_graph,'') displayGraph,(SELECT COUNT(*) from live_log_person llp where llp.chat_room_id=lr.chat_room_id GROUP BY chat_room_id) peopleCount");
		sql.append(" FROM(live_room lr,web_user wu)");
		sql.append(
				" LEFT JOIN live_log ll ON ll.chat_room_id=lr.chat_room_id WHERE lr.user_id=wu.user_id and lr.type IN (2,3)  and `status`=1  GROUP BY lr.chat_room_id  ORDER BY lr.start_time)");
		sql.append(" UNION");

		sql.append(
				" (SELECT wu.user_id id,IFNULL(wu.head_img,'') headImg,IFNULL(wu.nick_name,'') name,lr.type,IFNULL(lr.live_img,'') liveImg,IFNULL(lr.location,'') location,IFNULL(lr.live_name,'') personSign,lr.chat_room_id chatRoomId,IFNULL((SELECT llg.pull_url from live_log llg where ll.chat_room_id=llg.chat_room_id   ORDER BY llg.start_time desc LIMIT 1),'') liveUrl,IFNULL((SELECT llg.live_uuid from live_log llg where ll.chat_room_id=llg.chat_room_id   ORDER BY llg.start_time desc LIMIT 1),'') liveUuid,IFNULL(ll.display_graph,'') displayGraph,(SELECT COUNT(*) from live_log_person llp where llp.chat_room_id=lr.chat_room_id GROUP BY chat_room_id) peopleCount");
		sql.append(" FROM(live_room lr,web_user wu)");
		sql.append(
				" LEFT JOIN live_log ll ON ll.chat_room_id=lr.chat_room_id WHERE lr.user_id=wu.user_id and lr.type =1  and `status`=1  GROUP BY lr.chat_room_id  ORDER BY people_count)");
		List list = getJdbcTemplate().queryForList(sql.toString());
		return list;
	}

	public List getshareWordsForBefore() {
		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT content from share_word where is_show=1 and is_del=0 and type=1 ");
		List list = getJdbcTemplate().queryForList(sql.toString());
		return CollectionUtils.isNotEmpty(list) ? list : null;
	}

	public List getshareWordsForAfter() {
		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT content from share_word where is_show=1 and is_del=0 and type=2 ");
		List list = getJdbcTemplate().queryForList(sql.toString());
		return CollectionUtils.isNotEmpty(list) ? list : null;
	}

	/**
	 * 更改直播名称和描述
	 */
	public int updateLiveRoomForMonitor(String liveImg, String liveName, String anthId) {
		Timestamp now = new Timestamp(new Date().getTime());
		String sql = "update live_room lr set lr.live_img = ?, lr.live_name = ?, lr.update_time = ? where lr.user_id = ?";
		Object[] o = new Object[] { liveImg, liveName, now, anthId };
		return jdbcTemplate.update(sql, o);
	}
}
